#!/usr/bin/env python2
#-*- coding: utf-8 -*-

import os
import web
import json

from sqlalchemy.orm.exc import NoResultFound
from Umpweb.base import render_jinja
from Umpweb.db import api as db_api
from Umpweb.common import utils
from Umpweb.common.utils import login_required
from Umpweb.base import session, _, render_jinja

urls = (
        '/list',             'AccessControl',
        '/grid',             'GridAccessControl',
        '/create',           'AccessControlCreate',
        '/update',           'AccessControlUpdate',
        '/delete',           'AccessControlDelete',
)

app = web.application(urls, locals())
render = render_jinja('static/templates/access_control', encoding='utf-8',)

class AccessControl:
    @login_required
    def GET(self):
        web.header("Content-Type", "text/plain")
        return render.access_control_list()

class AccessControlCreate:
    @login_required
    def GET(self):
        return render.access_control_create()

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        values = dict(**web.input())

        body = {"AccessControlCreate":{'params':values}}
        return utils.web_return(body)

class AccessControlDelete:

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        body = {"AccessControlDelete":{'params':{'id':x.get('id').strip()}}}
        return utils.web_return(body)
        
class AccessControlUpdate:

    @login_required
    def GET(self):
        x = web.input()
        policy = db_api.access_control_get(x.get('id'))
        print policy.initiatorName
        print policy.iprange
        return render.access_control_update(policy=policy)

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        values = dict(**web.input())
        body = {"AccessControlUpdate": {'params': values}}
        return utils.web_return(body)

class GridAccessControl:
    def POST(self):
        web_input = web.input()
        filters = {}
        page, total, records, rows = \
                utils.grid_rows_query(db_api.policy_table, web_input, filters=filters)

        for policy in rows:
            volumes = db_api.volume_get_with_policy(policy.id)
            policy.volume_len = len(volumes)

        cells = ['id', 'name', 'iprange', 'initiatorName', 'volume_len', 'username', 'created_at']

        rows_json = utils.grid_json(
                page, total, records, rows, 'id', cells)
        web.header("Content-Type", "application/json")
        return rows_json
